(() => {
	// forEach兼容处理
	if (typeof(HTMLCollection.prototype.forEach) === "undefined") {
		HTMLCollection.prototype.forEach = Array.prototype.forEach;
	}
	if (typeof(NodeList.prototype.forEach) === "undefined") {
		NodeList.prototype.forEach = Array.prototype.forEach;
	}
	// 加载样式和脚本
	const firstStyle = document.querySelector('link[rel="stylesheet"]');
	function loadStyle(url) {
		const style = firstStyle.cloneNode(true);
		style.href = url;
		firstStyle.parentElement.insertBefore(style, firstStyle);
	}
	function loadScript(url, callback) {
		const script = document.createElement('script');
		script.src = url;
		script.async = true;
		if (callback) {
			script.onload = callback;
		}
		document.body.appendChild(script);
	}
	// AliCDN支持合并请求，故做此封装
	let cdnScripts = [];
	let cdnStyles = [];
	let cdnTimer = null;
	let cdnCallback = [];
	function loadScriptFromCdn(url, callback) {
		if (url && !cdnScripts.includes(url)) {
			cdnScripts.push(url);
		}
		if (callback) {
			cdnCallback.push(callback);
		}
		runCdnTimer();
	}
	function loadStyleFromCdn(url) {
		if (!cdnStyles.includes(url)) {
			cdnStyles.push(url);
		}
		runCdnTimer();
	}
	function runCdnTimer() {
		if (cdnTimer === null) {
			cdnTimer = setTimeout(() => {
				if (cdnScripts.length > 0) {
					// 将回调复制一份
					const callbacks = Array.from(cdnCallback);
					loadScript(getCdn('??' + cdnScripts.join(',')), () => callbacks.forEach(it => it()));
					cdnScripts = [];
					cdnCallback = [];
				}
				if (cdnStyles.length > 0) {
					loadStyle(getCdn('??' + cdnStyles.join(',')));
					cdnStyles = [];
				}
				clearTimeout(cdnTimer);
				cdnTimer = null;
			}, 0);
		}
	}
	function getCdn(url) {
		return 'https://g.alicdn.com/code/lib/' + url;
	}
	// 初始化基本layout
	function initLayout() {
		const menuButton = document.getElementById('menu-button');
		const backButton = document.getElementById('back-button');
		const layout_obfuscator = document.querySelector('.mdl-layout__obfuscator');
		const layout_drawer = document.querySelector('.mdl-layout__drawer');
		function toggleMenu() {
			if (layout_drawer.classList.contains('is-visible')) {
				layout_obfuscator.classList.remove('is-visible');
				layout_drawer.classList.remove('is-visible');
			} else {
				layout_obfuscator.classList.add('is-visible');
				layout_drawer.classList.add('is-visible');
			}
		}
		layout_obfuscator.addEventListener('click', toggleMenu);
		if (menuButton !== null) {
			menuButton.addEventListener('click', toggleMenu);
		}
		if (backButton) {
			backButton.addEventListener('click', () => {
				if (typeof(history.length) === "undefined" || history.length > 1) {
					history.go(-1);
				} else {
					window.location.href = '/';
				}
			});
		}
		//返回顶部
		document.getElementById('go-top').addEventListener('click', () => {
			window.scrollTo(0, 0);
		});
	}
	initLayout();
	// 随机背景图
	function initRandBackground() {
		const randImages = [
			'43895f6d-1d13-4085-a51f-75eb5690991e',
			'dadd008b-44c7-4e79-a1d2-8ddac72407e9',
			'5a0fedca-da4b-4456-bf3f-a5b4a904469f',
			'da21910d-5728-4064-a56d-7fa0903a0377',
			'd2ab9ada-a67d-4ffb-9838-fbc2fd68b8b0',
			'cf03bae4-475d-45a7-b097-f2cf00cb90e2'
		].map(it => `https://tianshu.alicdn.com/${it}.jpg`);
		document.querySelectorAll('.rand-background').forEach((e) => {
			const randNum = Math.floor(Math.random() * 6);
			e.style.backgroundImage = 'url(' + randImages[randNum] + ')';
		});
	}
	initRandBackground();
	//文章图片
	const articleImages = document.querySelectorAll('.article-image');
	if (articleImages.length > 0) {
		//lazyload
		loadScriptFromCdn('lazyloadjs/3.2.2/lazyload.min.js', () => {
			const l = lazyload({
				"offset": 200,
				"src": "data-src"
			});
			articleImages.forEach(e => l(e));
		});
		// 放大组件
		loadScript('https://g.alicdn.com/mylib/medium-zoom/1.0.5/dist/medium-zoom.min.js', function() {
			mediumZoom(articleImages);
		});
	}
	// markdown样式
	if (document.querySelector('.markdown-body')) {
		loadStyleFromCdn('github-markdown-css/3.0.1/github-markdown.min.css');
	}
	//分享插件
	function initShare() {
		const share = {
			"qzone": {
				"url": 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url={{URL}}&title={{TITLE}}&desc={{DESCRIPTION}}',
				"name": 'QQ空间'
			},
			"qq": {
				"url": 'http://connect.qq.com/widget/shareqq/index.html?url={{URL}}&title={{TITLE}}&desc={{DESCRIPTION}}',
				"name": 'QQ'
			},
			"weibo": {
				"url": 'http://service.weibo.com/share/share.php?url={{URL}}&title={{TITLE}}',
				"name": '微博'
			},
			"tieba": {
				"url": 'http://tieba.baidu.com/f/commit/share/openShareApi?url={{URL}}&title={{TITLE}}&desc={{DESCRIPTION}}&comment=',
				"name": '贴吧'
			},
			"qrcode": {
				"name": '二维码'
			},
			"douban": {
				"url": 'http://shuo.douban.com/!service/share?href={{URL}}&name={{TITLE}}&text={{DESCRIPTION}}&starid=0&aid=0&style=11',
				"name": '豆瓣'
			},
			"facebook": {
				"url": 'https://www.facebook.com/sharer/sharer.php?u={{URL}}',
				"name": 'Facebook'
			},
			"twitter": {
				"url": 'https://twitter.com/intent/tweet?text={{TITLE}}&url={{URL}}',
				"name": 'Twitter'
			}
		};
		const share_order = 'qrcode,weibo,tieba,qq,qzone,douban,facebook,twitter'.split(',');
		const share_list = document.getElementById('share_list');
		if (share_list) {
			share_order.forEach(e => {
				const n = document.createElement('li');
				n.classList.add('mdl-menu__item');
				//二维码单独处理
				if (e === 'qrcode') {
					n.classList.add('show_qrcode');
					n.setAttribute('data-url', window.location.href);
					n.innerHTML = '<a href="javascript:void(0);"><i class="iconfont icon-' + e +'"></i>' + share[e].name;
				} else {
					let desc = document.getElementsByTagName('meta')['description'].content;
					if (!desc) {
						desc = '';
					}
					let result = share[e].url;
					result = result.replace('{{URL}}', encodeURIComponent(window.location.href))
						.replace('{{TITLE}}', encodeURIComponent(document.title))
						.replace('{{DESCRIPTION}}', encodeURIComponent(desc));
					n.innerHTML = '<a href="' + result + '" target="_blank" rel="nofollow"><i class="iconfont icon-' + e +'"></i>' + share[e].name;
				}
				share_list.appendChild(n);
			});
		}
	}
	initShare();
	if (document.querySelector('.show_qrcode') && document.querySelector('.qrcode-dialog') === null) {
		const dialog = document.createElement('dialog');
		dialog.classList.add('qrcode-dialog');
		dialog.classList.add('mdl-dialog');
		dialog.innerHTML = '<h4 class="mdl-dialog__title">扫一扫</h4><div class="mdl-dialog__content"><img></div><div class="mdl-dialog__actions"><button type="button" class="mdl-button close">关闭</button></div>';
		document.body.appendChild(dialog);
		loadScriptFromCdn('qrcode-generator/1.4.4/qrcode.min.js');
		dialog.querySelector('.close').addEventListener('click', () => {
			dialog.close();
		});
	}
	//dialog兼容处理
	const dialogs = document.querySelectorAll('.mdl-dialog');
	if (dialogs.length > 0 && dialogs[0].showModal === undefined) {
		loadStyleFromCdn('dialog-polyfill/0.5.0/dialog-polyfill.min.css');
		loadScriptFromCdn('dialog-polyfill/0.5.0/dialog-polyfill.min.js', () => dialogs.forEach(it => dialogPolyfill.registerDialog(it)));
	}
	//显示二维码按钮
	function onQrbuttonClick() {
		const content = document.querySelector('.qrcode-dialog .mdl-dialog__content');
		const qr = qrcode(0, 'H');
		qr.addData(this.getAttribute('data-url'));
		qr.make();
		content.innerHTML = qr.createImgTag(Math.floor(230 / qr.getModuleCount()), 0);
		document.querySelector('.qrcode-dialog').showModal();
	}
	document.querySelectorAll('.show_qrcode').forEach(e => e.addEventListener('click', onQrbuttonClick));
	//代码高亮插件
	const pres = document.querySelectorAll('pre');
	if (pres.length > 0) {
		loadStyleFromCdn('SyntaxHighlighter/3.0.83/styles/shCore.min.css');
		loadStyleFromCdn('SyntaxHighlighter/3.0.83/styles/shThemeDefault.min.css');
		loadScriptFromCdn('SyntaxHighlighter/3.0.83/scripts/shCore.min.js');
		// 查找所有pre元素，并加载相应的高亮插件
		const brushes = {
			"bash": "Bash",
			"shell": "Bash",
			"cpp": "Cpp",
			"c": "Cpp",
			"c#": "CSharp",
			"c-sharp": "CSharp",
			"csharp": "CSharp",
			"css": "Css",
			"java": "Java",
			"js": "JScript",
			"javascript": "JScript",
			"php": "Php",
			"text": "Plain",
			"plain": "Plain",
			"sass": "Sass",
			"scss": "Sass",
			"sql": "Sql",
			"xml": "Xml",
			"html": "Xml"
		};
		pres.forEach(it => {
			const brushName = it.className.replace('brush: ', '');
			if (it.className.includes('brush') && brushName && typeof(brushes[brushName]) !== "undefined") {
				loadScriptFromCdn('SyntaxHighlighter/3.0.83/scripts/shBrush' + brushes[brushName] + '.min.js');
			}
		});
		loadScriptFromCdn(null, () => {
			SyntaxHighlighter.defaults.toolbar = false;
			SyntaxHighlighter.highlight();
		});
	}
	window.loadScript = loadScript;
	window.loadStyle = loadStyle;
})();